//
//  LHTabBarController.swift
//  Swift3.0WB
//
//  Created by 美食家 on 17/3/28.
//  Copyright © 2017年 不孤独的美食家. All rights reserved.
//

import UIKit
import SVProgressHUD
/** 主控制器  */
class LHTabBarController: UITabBarController {
    /** 计时器  */
    var timer : Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupControllers()
        setupComposeBtn()
        setupTimer()
        /** 添加新特性界面 */
        setupNewFeatureView()
        delegate=self
        
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogon), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
    }
    
    deinit {
        /** 销毁计时器  */
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    /**  使用代码控制设备设置屏幕支持方向 */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
    
          return .portrait
    }
    
    /**  Use of unresolved identifier 'composeButtonDidClick' */
    @objc  func composeButtonDidClick() -> Void{
                print("加号按钮被点击")
        let vc = UIViewController()
        let nav=UINavigationController(rootViewController: vc)
        present(nav, animated:true, completion: nil)
    }
    
    /// MARK - 通知监听登录按钮的方法
    @objc func userLogon(noti:Notification){
         print("监听到需要登录的通知,包含消息有："+"\(noti)")
        var when = DispatchTime.now()
        if noti.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录过期,请重新登录")
            when=DispatchTime.now()+2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when, execute: {
            
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let vc = UINavigationController(rootViewController: OAuthViewController())
            
            self.present(vc, animated: true, completion: nil)
            
        })
        
        
    }
    
    /**写微博的懒加载按钮 */
    lazy var composeButton: UIButton=UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
  }

extension LHTabBarController:UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let index = childViewControllers.index(of: viewController)
        
        if selectedIndex == 0 && index == selectedIndex {
            print("切换到首页，并点击了他")
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! LHHomeController
            
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: {
                print("切换到首页，dianji，刷新数据")
                vc.loadData()
            })
            
            vc.tabBarItem.badgeValue=nil
            UIApplication.shared.applicationIconBadgeNumber=0
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
 
}

extension LHTabBarController {
    
     func setupNewFeatureView(){
        
        if !LHNetWorkManager.shared.userLogon {
            return
        }
    
        let v = isNewVersion ?  WBNewFeatureView.WBNewFeatureView() : WBWelcomeView.welcomeView()
        
        view.addSubview(v)
    
    }
    
    private var isNewVersion : Bool{
        
        let currentVersion=Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
//        print(currentVersion)
        let versionPath : String=("version" as NSString).cz_appendDocumentDir()
        let sandBoxVersion=(try? String(contentsOfFile: versionPath)) ?? ""
//        print(sandBoxVersion)
        _ = try? currentVersion.write(toFile: versionPath, atomically: true, encoding: .utf8)
        return currentVersion != sandBoxVersion
    }
    
}

// MARK: 设置定时器

extension LHTabBarController{
    
    func setupTimer() -> Void {
        
        timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
        }
    
    func updateTimer() -> Void{
        
        if !LHNetWorkManager.shared.userLogon {
           return
        }
        
        LHNetWorkManager.shared.unreadCount { (unreadCount) in
            
            let count=(unreadCount>99 ? "99+" : "\(unreadCount)")
            self.tabBar.items?[0].badgeValue = unreadCount>0 ? count :nil
            print("有\(unreadCount)条微博消息未读")
            UIApplication.shared.applicationIconBadgeNumber=unreadCount
        }
    }

}


// MARK: 设置界面

extension LHTabBarController{
    
    func setupComposeBtn(){
        /** Use of unresolved identifier 'composeButton' */
        tabBar.addSubview(composeButton)
        let count=CGFloat(childViewControllers.count)
        let w=tabBar.bounds.width / count
        composeButton.frame=tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        composeButton.addTarget(self, action: #selector(composeButtonDidClick), for: .touchUpInside)
    }
    
     /** 设置所有子控制器 */
    func  setupControllers() {
        
        let docDir=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let pathJson=(docDir as NSString).appendingPathComponent("main.json")
        
        var data=NSData(contentsOfFile: pathJson)
        
        if data == nil {
        let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data=NSData(contentsOfFile: path!)
        }
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [[String : AnyObject]] else {
            return
        }
        
        
//        let array : [[String : AnyObject]] = ([
//            ["clsname": "LHHomeController", "title": "首页", "imageName":"home",
//             "visitorInfo" : ["imageName":"" , "message":"关注一些人，回这里看有什么惊喜"]
//            ],
//            ["clsname": "LHDiscoverController", "title": "发现", "imageName":"discover",
//             "visitorInfo" : ["imageName":"visitordiscover_image_message" , "message":"登陆后，比尔呢评论你的微博，发给你的消息，都会在这里收到通知"]
//            ],
//            ["clsname": "LHComposeController"],
//            ["clsname": "LHMessageController",  "title": "消息", "imageName":"message_center",
//             "visitorInfo" : ["imageName":"visitordiscover_image_message" , "message":"登陆后，最新，最热微博尽在掌握，不再与实事潮流擦肩而过"]
//            ],
//            ["clsname": "LHProfileControllerViewController", "title": "我","imageName":"profile",
//             "visitorInfo" : ["imageName":"visitordiscover_image_profile" , "message":"登陆后，你的微博，相册会在这里展示"]
//            ],
//            ] as AnyObject) as! [[String : AnyObject]]
        
        /** 测试数据格式是否正确 */
       // (array as NSArray).write(toFile: "/Users/apple/Desktop/SinaWeibo.plist", atomically: true)
        
//       let data = try!JSONSerialization.data(withJSONObject: array, options: .prettyPrinted)
//       (data as NSData).write(toFile: "/Users/apple/Desktop/SinaWeibo.json", atomically: true)
    
        var arrayM=[UIViewController]()
        
        for dict in array {
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
        
    }
    
    private func controller(dict:[String:AnyObject]) -> UIViewController{
                
        /** 1 取得字典内容 */
        guard let className=dict["clsname"] as? String,
              let title=dict["title"] as? String,
              let imageName=dict["imageName"] as? String,
              let vc=NSClassFromString((Bundle.main.namespace+"."+className) as String) as? LHBaseController.Type,
              let visitorDict = dict["visitorInfo"] as? [String: String]
              else {
                  return UIViewController()
               }
        
        /** 2 设置值 */
        let v = vc.init()
        v.visitorDict=visitorDict
        v.title=title;
        
        v.tabBarItem.image=UIImage(named:"tabbar_"+imageName)
        v.tabBarItem.selectedImage=UIImage(named:"tabbar_"+imageName+"_selected")?.withRenderingMode(.alwaysOriginal)
        
        v.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange],
                                            for: .highlighted)
        v.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)],
                                            for: UIControlState(rawValue:0))
        
        let nav = LHNavigationController(rootViewController: v)
        
        /** 3 返回控制器 */
        return nav
        
    }
}
